"""
!!!BETA VERSION!!!
STILL IN TESTING, USE AT YOUR *OWN* RISK
"""

try:
    import _winreg as winreg
except ImportError:
    import winreg

IGNORE_WORKSPACES = {
    "_registryRoot",
    "Perforce",
    "ToolsFolders",
}

#private
def _startup():
   reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "SOFTWARE\\Saber3D\\Workspace")
   _preparePS(str(winreg.QueryValueEx(reg_key, "workspacePs_default")[0]))
   _preparePS(str(winreg.QueryValueEx(reg_key, "workspacePs")[0]))

def _get_ins_pos(root, key):
   ins_to = _internalPS
   for item in root:
      ins_to = ins_to[item]
   return ins_to

def _preparePS(workspaces_ps):
   pslines = workspaces_ps.split("\n")
   root = []
   for line in pslines:
      sectionExit = False
      idx = line.find("}")
      if idx != -1:
         line = line[:idx]
         sectionExit = True
      idx = line.find("=")
      if idx != -1:
         key = line[:idx].strip()
         value = line[idx+1:].replace("\\\\","\\").strip(" \"")
         ins_to = _get_ins_pos(root, key)
         if value == "{":
            if key not in ins_to:
               ins_to[key] = dict()
            root.append(key)
         else:
            ins_to[key] = value
      if sectionExit == True:
         root.pop()

#public

# set default workspace
def setWorkspace(ws_name):
   globals()["_ws_name"] = ws_name

# returns name of default workspace
def getWorkspace():
   return _ws_name

# get record from default workspace
def getRecordWs(key):
   if _ws_name != "":
      return getRecord([_ws_name], key)
   return ""

# get record from any workspace
def getRecord(root, key):
   ins_to = _get_ins_pos(root, key)
   if key in ins_to:
      value = ins_to[key]
      idx = value.find("<")
      while idx != -1:
         idx_end = value.find(">")
         support_key = value[idx+1:idx_end]
         support_value = getRecord(root, support_key)
         value = value[0:idx] + support_value + value[idx_end+1:]
         idx = value.find("<")
      return value
   return ""

_internalPS = dict()
_ws_name = ""
_startup()

def getWorkspaceList():
    return tuple(p for p in _internalPS.keys() if p not in IGNORE_WORKSPACES)